﻿import React, {PureComponent} from 'react';
import * as PropTypes from 'prop-types'
import {StoreManager} from "@/stores";
import {FormStore} from "@/components/Form";

class Form extends PureComponent {

    static propTypes = {
        name: PropTypes.oneOfType([PropTypes.string, PropTypes.symbol]).isRequired,
        inline: PropTypes.bool,
        showErrorsOnChange: PropTypes.bool,
        showErrorsOnBlur: PropTypes.bool,
    }

    static defaultProps = {
        showErrorsOnChange: true,
        showErrorsOnBlur: true
    }

    static childContextTypes = {
        formSettings: PropTypes.object
    }

    constructor(props, context) {
        super(props, context)
        this.store = StoreManager.create(new FormStore(props))
    }

    getChildContext() {
        return {
            formSettings: {
                store: this.store,
                showErrorsOnChange: this.props.showErrorsOnChange,
                showErrorsOnBlur: this.props.showErrorsOnBlur
            }
        }
    }

    componentWillUnmount() {
        StoreManager.delete(this.store)
    }

    onSubmit = (event) => {
        this.store.validate()
        if (this.store.hasErrors) {
            event.preventDefault()
            return
        }
        if (this.props.onSubmit) {
            this.props.onSubmit(event)
        }
    }

    render() {
        const {children} = this.props
        return (
            <form onSubmit={this.onSubmit} children={children}/>
        )
    }
}

export {Form}

